package org.yzh.web.waterMeter.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.yzh.framework.codec.MessageEncoder;
import org.yzh.framework.commons.transform.ByteBufUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 808协议编码器
 *
 * @author zhihao.ye (yezhihaoo@gmail.com)
 */
public class WaterMeterMessageEncoder extends MessageEncoder {

    @Override
    public ByteBuf sign(ByteBuf buf) {

        ByteBuf checkBuf = buf.slice(6,buf.writerIndex()-6);
        byte checkCode = ByteBufUtils.sum(checkBuf);
        buf.writeByte(checkCode);
        buf.writeByte(0x16);
        return buf;
    }

    /**
     * 转义处理
     */
    @Override
    public ByteBuf escape(ByteBuf source) {

        //修正长度
        this.correctLengthByteBuf(source);

        //提取报文长度进行互换
        ByteBuf lengthBuf = ByteBufUtils.reverseByteBuf(ByteBufUtils.getLengthByteBuf(source));

        //提取终端号进行互换
        ByteBuf terminalInfoBuf = ByteBufUtils.reverseByteBuf(ByteBufUtils.getTerminalInfoByteBuf(source));

        //提取用户报文进行转换
        ByteBuf userInfoBuf = ByteBufUtils.reverseByteBuf(ByteBufUtils.getUserInfoByteBuf(source));


        return source;
    }

    /**
     * 修改报文长度
     * @param source 源报文
     * @return
     */
    public void correctLengthByteBuf(ByteBuf source){
        //消息长度处理
        int length = source.getUnsignedShort(1);
        length = (length+12) << 2 | 0x2;

        source.setByte(1,length  >>> 8);
        source.setByte(2,length);
        source.setByte(3,length  >>> 8);
        source.setByte(4,length);
    }

    public static void main(String[] args) {
        int length = 0;
        length = (length+0x00ff) << 2 | 0x2;

        int a =  length >>> 8;

        System.out.println(length);
    }



}